const { app, BrowserWindow } = require('electron');
///引入ipcMain，才能和预加载脚本通信
const { ipcMain } = require('electron');
///node.js写入数据
const fs = require('fs');
const os = require('os');
const path = require('node:path');

// 判断是否在development环境下
if (process.env.NODE_ENV === 'development') {
  // 如果electron是全局安装，指定electron可执行文件
  const electronPath = require('child_process')
    .execSync('npm root -g')
    .toString().trim() + '/electron/cli.js';
  // 引用全局安装的 electron-reload
  require('/usr/local/lib/node_modules/electron-reload')(path.join(__dirname), {
    electron: electronPath, // 指定 electron 可执行文件
    hardResetMethod: 'exit', // 使用 'exit' 方式强制重启
    ignored: /node_modules|[\/\\]\.///忽略文件
  });
}
// Handle creating/removing shortcuts on Windows when installing/uninstalling.
if (require('electron-squirrel-startup')) {
  app.quit();
}


const createWindow = () => {
  // Create the browser window.
  const mainWindow = new BrowserWindow({
    width: 1000,
    height: 600,
    webPreferences: {
      ///把主进程根预加载脚本绑定起来
      preload: path.join(__dirname, 'preload.js'),
    },
  });

  ///订阅信号
  ipcMain.on('file_save', writeFile);
  ///订阅信号
  ipcMain.handle('file_read', readFile);
  // and load the index.html of the app.
  mainWindow.loadFile(path.join(__dirname, 'index.html'));

  // Open the DevTools.
  //mainWindow.webContents.openDevTools();
};

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.whenReady().then(() => {
  createWindow();

  // On OS X it's common to re-create a window in the app when the
  // dock icon is clicked and there are no other windows open.
  app.on('activate', () => {
    if (BrowserWindow.getAllWindows().length === 0) {
      createWindow();
    }
  });
});


// Quit when all windows are closed, except on macOS. There, it's common
// for applications and their menu bar to stay active until the user quits
// explicitly with Cmd + Q.
app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit();
  }
});

// In this file you can include the rest of your app's specific main process
// code. You can also put them in separate files and import them here.



function writeFile(event, data, _) {
  let filePath;
  const platform = os.platform();
  switch (platform) {
    case 'win32':
      filePath = path.join('D:\\', 'hello.txt');
      break;
    case 'darwin':
      filePath = path.join(os.homedir(), 'Desktop', 'hello.txt');
      break;
    case 'linux':
      filePath = path.join(os.homedir(), 'Desktop', 'hello.txt');
      break;
    default:
      break;
  }
  // 写入文件
  try {
    fs.writeFileSync(filePath, data);
    console.log(`文件已成功写入到：${filePath}`);
  } catch (err) {
    console.error('写入文件失败:', err);
  }
}

function readFile() {
  let filePath;
  const platform = os.platform();
  switch (platform) {
    case 'win32':
      filePath = path.join('D:\\', 'hello.txt');
      break;
    case 'darwin':
      filePath = path.join(os.homedir(), 'Desktop', 'hello.txt');
      break;
    case 'linux':
      filePath = path.join(os.homedir(), 'Desktop', 'hello.txt');
      break;
    default:
      break;
  }
  // 写入文件
  try {
    console.log(`文件已成功读取：${filePath}`);
    return fs.readFileSync(filePath).toString();
  } catch (err) {
    console.error('读取文件失败:', err);
    return '读取文件失败:' + err;
  }
}
